use std::env;

use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct AppConfig {
    pub logging: Logging,
    pub server: Server,
    pub datasource: Datasource,
}

#[derive(Debug, Deserialize)]
pub struct Logging {
    pub level: String,
    pub filepath: String,
    pub filename: String,
}

#[derive(Debug, Deserialize)]
pub struct Server {
    pub listen: String,
}

#[derive(Debug, Deserialize)]
pub struct Datasource {
    pub url: String,
}

impl AppConfig {
    pub fn new() -> Self {
        let args = env::args().collect::<Vec<_>>();
        let mut config = config::Config::builder()
            .add_source(config::File::with_name("config/application.yaml"));

        if args.len() > 1 {
            config = config.add_source(
                config::File::with_name(&format!("config/application-{}.yaml", args[1]))
                    .required(false),
            );
        }
        let config = config.build().unwrap();
        config.try_deserialize().unwrap()
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        Self::new()
    }
}
